package com.example.myapplication

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class DepartmentManagementActivity : AppCompatActivity() {
    
    private lateinit var listView: ListView
    private lateinit var buttonAddDepartment: Button
    private lateinit var databaseHelper: DatabaseHelper
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_department_management)
        
        databaseHelper = DatabaseHelper(this)
        
        initViews()
        loadDepartments()
    }
    
    private fun initViews() {
        listView = findViewById(R.id.listViewDepartments)
        buttonAddDepartment = findViewById(R.id.buttonAddDepartment)
        
        buttonAddDepartment.setOnClickListener {
            showAddDepartmentDialog()
        }
    }
    
    private fun loadDepartments() {
        val departments = databaseHelper.getAllDepartments()
        val users = databaseHelper.getAllUsers()
        
        val departmentList = departments.map { dept ->
            val admin = users.find { it.id == dept.adminId }
            val userCount = users.count { it.department == dept.name }
            "${dept.name} - 管理员: ${admin?.realName ?: "未设置"} - 用户数: $userCount"
        }
        
        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, departmentList)
        listView.adapter = adapter
        
        listView.setOnItemClickListener { _, _, position, _ ->
            showDepartmentDetails(departments[position])
        }
    }
    
    private fun showAddDepartmentDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_department, null)
        val editTextName = dialogView.findViewById<EditText>(R.id.editTextDepartmentName)
        val editTextDesc = dialogView.findViewById<EditText>(R.id.editTextDepartmentDesc)
        val editTextPhone = dialogView.findViewById<EditText>(R.id.editTextDepartmentPhone)
        val editTextAdminName = dialogView.findViewById<EditText>(R.id.editTextDepartmentAdminName)
        AlertDialog.Builder(this)
            .setTitle("添加科室")
            .setView(dialogView)
            .setPositiveButton("添加") { _, _ ->
                val name = editTextName.text.toString().trim()
                val desc = editTextDesc.text.toString().trim()
                val phone = editTextPhone.text.toString().trim()
                val adminName = editTextAdminName.text.toString().trim()
                if (name.isEmpty()) {
                    Toast.makeText(this, "请输入科室名称", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                val department = Department(
                    name = name,
                    adminId = 0L,
                    isActive = true,
                    description = desc,
                    contactPhone = phone,
                    adminName = adminName
                )
                val result = databaseHelper.addDepartment(department)
                if (result > 0) {
                    Toast.makeText(this, "科室添加成功", Toast.LENGTH_SHORT).show()
                    loadDepartments()
                } else {
                    Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun showDepartmentDetails(department: Department) {
        val users = databaseHelper.getAllUsers()
        val admin = users.find { it.id == department.adminId }
        val departmentUsers = users.filter { it.department == department.name }
        val details = """
            科室名称: ${department.name}
            简介: ${department.description}
            联系电话: ${department.contactPhone}
            负责人: ${department.adminName.ifEmpty { admin?.realName ?: "未设置" }}
            用户数量: ${departmentUsers.size}
            状态: ${if (department.isActive) "启用" else "停用"}
            \n用户列表:\n${departmentUsers.joinToString("\n") { "- ${it.realName} (${it.username})" }}
        """.trimIndent()
        val builder = AlertDialog.Builder(this)
            .setTitle("科室详情")
            .setMessage(details)
            .setPositiveButton("确定", null)
            .setNeutralButton("成员管理") { _, _ ->
                showDepartmentMemberDialog(department)
            }
        if (department.isActive) {
            builder.setNegativeButton("停用科室") { _, _ ->
                updateDepartmentStatus(department, false)
            }
        } else {
            builder.setNegativeButton("启用科室") { _, _ ->
                updateDepartmentStatus(department, true)
            }
        }
        builder.show()
    }
    
    private fun updateDepartmentStatus(department: Department, enable: Boolean) {
        val updated = department.copy(isActive = enable)
        databaseHelper.updateDepartment(updated)
        Toast.makeText(this, if (enable) "科室已启用" else "科室已停用", Toast.LENGTH_SHORT).show()
        loadDepartments()
    }
    
    private fun showDepartmentMemberDialog(department: Department) {
        val users = databaseHelper.getAllUsers().filter { it.department == department.name }
        val userNames = users.map { it.realName + " (" + it.username + ")" }
        val adminIndex = users.indexOfFirst { it.id == department.adminId }
        AlertDialog.Builder(this)
            .setTitle("成员管理")
            .setSingleChoiceItems(userNames.toTypedArray(), adminIndex) { dialog, which ->
                val selectedUser = users[which]
                if (selectedUser.id != department.adminId) {
                    // 转移管理员
                    val updated = department.copy(adminId = selectedUser.id, adminName = selectedUser.realName)
                    databaseHelper.updateDepartment(updated)
                    Toast.makeText(this, "已将${selectedUser.realName}设为管理员", Toast.LENGTH_SHORT).show()
                    loadDepartments()
                    dialog.dismiss()
                }
            }
            .setNegativeButton("移除成员") { _, _ ->
                // 仅移除普通成员，不能移除管理员
                val removable = users.filter { it.id != department.adminId }
                if (removable.isEmpty()) {
                    Toast.makeText(this, "无可移除成员", Toast.LENGTH_SHORT).show()
                    return@setNegativeButton
                }
                val names = removable.map { it.realName + " (" + it.username + ")" }.toTypedArray()
                AlertDialog.Builder(this)
                    .setTitle("选择要移除的成员")
                    .setItems(names) { _, idx ->
                        val user = removable[idx]
                        databaseHelper.removeUserFromDepartment(user.id)
                        Toast.makeText(this, "已移除${user.realName}", Toast.LENGTH_SHORT).show()
                        loadDepartments()
                    }
                    .setNegativeButton("取消", null)
                    .show()
            }
            .setPositiveButton("关闭", null)
            .show()
    }
} 